package top.yamhk.agent.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 加密类 包括DES,DES3,AES和RSA加密
 * DES加密算法
 * AES加密算法
 * RSA加密算法
 * Base64加密算法
 * MD5加密算法
 * SHA1加密算法
 *
 * @author 庆 HongKong
 * @date 2020/9/19 16:08
 */
@Slf4j
public class CipherUtil {

    public static final String DEFAULT_AES_KEY = "1234567890123456";
    public static final String DEFAULT_RSA_PUB_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5MHZVWSroThWrImaDc/r/4t30cqtHAM11PbCx0BcMhq77KM6TzcU1P8kXwm6CbWKujJ5dLX8Msc4MDvbMhcGPLql+bmtS1fVrKwDUkicGroOXwwvDc/CMf7SEbi1Qycy+ho4wNq7rwFe5GN9xrxEQObhVmO/egZg5qbvCSXlzDQIDAQAB";
    public static final String DEFAULT_RSA_PRI_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALkwdlVZKuhOFasiZoNz+v/i3fRyq0cAzXU9sLHQFwyGrvsozpPNxTU/yRfCboJtYq6Mnl0tfwyxzgwO9syFwY8uqX5ua1LV9WsrANSSJwaug5fDC8Nz8Ix/tIRuLVDJzL6GjjA2ruvAV7kY33GvERA5uFWY796BmDmpu8JJeXMNAgMBAAECgYEArvRc5zcNdVjH2dzvEoOQ/wx6+oUW0Uat1HSKqQJZtCjNyVR9DWAaTrtLJRo4QxpKX3NT7d2cqQaWDghZG1HGUP4ed/tQ6/rYIyxxi7hGXmOfPli/3xM2S0jiEwiluE8n1MZ4/jRAE9wkf5trJ9RjlGqEBBayf0iPljRWZJMgoPUCQQDlhHo4TlfTSV/M5q37QIKXMtJjre2wsXSbJHO1SeqI1EFdcWX6bs4i29lqyVZLwKATWPe75P7Xy2QDsJfRQQK/AkEAzo6ctmJpzxl07753mwOc/pIi+ENDE1ekpDVzFoDIaX+YPMx5iZKEA6aei+KVXQ6E9I9cGV+kteHcSP1dWE7ZMwJBAIUWRpCzzPV1jJmSAby5cYAfNiQazMMygz0a7AVpcRgajDSU9t86tUk9Vls3mFSgw7G0WyKW7LdQ9xO0qLPsEJ0CQQDAr6jhOs0ZtNWxECzjHmvFzu1wSs63rHqZ9IJ364sJX03U6ao2+8bK4RPlymkrde/xdAqmYOJ2CUxFipUZW/ShAkA99hmivBuJOsuXE2OVhcMAitLKXYUUbX6wlM/QN/ayA6Nv4C6PGs4iiMr8mtO2hmX9PHFpFjBo3P7Jk4JyYjPW";

    /**
     * 私有构造方法
     */
    private CipherUtil() {
    }

    /**
     * 对称加密 key必须为16位
     * 密码箱
     *
     * @param str str
     * @param key key
     * @return String
     * @throws Exception Exception
     */
    public static String aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * aes解密
     *
     * @param str str
     * @param key key
     * @return String
     * @throws Exception Exception
     */
    public static String aesDecrypt(String str, String key) throws Exception {
        if (str == null || key == null) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(str));
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static String defaultEncrypt(String content) {
        try {
            return aesEncrypt(content, DEFAULT_AES_KEY);
        } catch (Exception e) {
            log.error("加密失败-{}-{}", content, e.getMessage(), e);
            return "";
        }
    }

    public static String defaultDecrypt(String content) {
        try {
            return aesDecrypt(content, DEFAULT_AES_KEY);
        } catch (Exception e) {
            log.error("解密失败-{}-{}", content, e.getMessage(), e);
            return "";
        }
    }

    public static String defaultEncryptWithEncode(String content) {
        try {
            return URLEncoder.encode(defaultEncrypt(content), "UTF-8");
        } catch (Exception e) {
            log.error("Encode失败-{}-{}", content, e.getMessage());
            return "";
        }
    }

    public static String defaultDecryptWithDecode(String content) {
        try {
            return defaultDecrypt(URLDecoder.decode(content, "UTF-8"));
        } catch (Exception e) {
            log.error("Decode失败-{}-{}", content, e.getMessage());
            return "";
        }
    }

    /**
     * 脱敏-手机号
     *
     * @param phone phone
     * @return String
     */
    public static String hidePhone(String phone) {
        if (phone.length() == 11) {
            return phone.substring(0, 3) + "****" + phone.substring(7, 11);
        } else {
            return "***-****-****";
        }
    }

    /**
     * 脱敏-姓名
     *
     * @param customerName customerName
     * @return String
     */
    public static String hideName(String customerName) {
        if (customerName == null) {
            return null;
        }
        if (customerName.length() > 4) {
            return StrUtil.sub(customerName, 1, 0) + "**" + StrUtil.sub(customerName, customerName.length(), -1);
        } else if (customerName.length() > 2) {
            return StrUtil.hide(customerName, 1, customerName.length() - 1);
        } else {
            return StrUtil.hide(customerName, 1, customerName.length());
        }
    }

    public static String rsaEncrypt(String content) {
        RSA rsa = new RSA(null, DEFAULT_RSA_PUB_KEY);
        return rsa.encryptBase64(content, KeyType.PublicKey);
    }

    public static String rsaDecrypt(String content) {
        RSA rsa = new RSA(DEFAULT_RSA_PRI_KEY, null);
        return rsa.decryptStr(content, KeyType.PrivateKey);
    }
}